#pragma once
#include <vector>
#include <semaphore.h>
#include <iostream>
#include <pthread.h>
#include"caculate_task.hpp"
using namespace std;

template <class T>
class ringQueue
{
public:
    ringQueue()
        : _head(0), _tail(0), _size(0), _capacity(5)
    {
        _queue.resize(_capacity);
        sem_init(&_spaceSem, 0, _capacity);
        sem_init(&_dataSem, 0, 0);
        pthread_mutex_init(&_c_mutex, nullptr);
        pthread_mutex_init(&_p_mutex, nullptr);
    }

    void push(T &data,const string& name)
    {
        sem_wait(&_spaceSem);
        pthread_mutex_lock(&_p_mutex);

        data.createTask(name);
        _queue[_tail] = data;
        _tail++;
        _tail %= _capacity;
        _size++;
        sem_post(&_dataSem);
        pthread_mutex_unlock(&_p_mutex);
    }

    void pop(T &data,const string& name)
    {
        sem_wait(&_dataSem);
        pthread_mutex_lock(&_c_mutex);
        data = _queue[_head];
        _head++;
        _head %= _capacity;
        _size--;
        data();
        data.getAnswer(name);
        pthread_mutex_unlock(&_c_mutex);
        sem_post(&_spaceSem);
    }

    ~ringQueue()
    {
        pthread_mutex_destroy(&_c_mutex);
        pthread_mutex_destroy(&_p_mutex);
    }

private:
    vector<T> _queue;
    size_t _head;
    size_t _tail;
    size_t _size;
    size_t _capacity;
    sem_t _spaceSem;
    sem_t _dataSem;
    pthread_mutex_t _p_mutex;
    pthread_mutex_t _c_mutex;
};
